//
//  ViewController.m
//  VideoDemo
//
//  Created by Bernie on 2018/7/19.
//  Copyright © 2018年 Bernie. All rights reserved.
//

#import "ViewController.h"
#import <GPUImage.h>
#import "GPUimageTransparent.h"

#import <Photos/Photos.h>
#import <AssetsLibrary/ALAssetsLibrary.h>
@interface ViewController () {
    AVMutableCompositionTrack *AudioTrack;
    AVAssetExportSession *exporter;
}

@property (nonatomic , strong) NSMutableArray *datalist;
@property (nonatomic , strong) GPUImageVideoCamera *videoCamera;
@property (nonatomic , strong) GPUImageMovieWriter *movieWriter;
@property (nonatomic , strong) GPUImageView *filterView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    _videoCamera = [[GPUImageVideoCamera alloc] initWithSessionPreset:AVCaptureSessionPresetiFrame960x540 cameraPosition:AVCaptureDevicePositionFront];
    _videoCamera.horizontallyMirrorFrontFacingCamera = YES;
    _videoCamera.outputImageOrientation = [UIApplication sharedApplication].statusBarOrientation;
    
    [_videoCamera startCameraCapture];
    
    _filterView = [[GPUImageView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    
    [_videoCamera addTarget:_filterView];
    
    [self.view addSubview: _filterView];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"录制" style:UIBarButtonItemStyleDone target:self action:@selector(onClick:)];
    
}

- (void)onClick:(UIBarButtonItem *)sender {
    
    NSString *pathToMovie = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/%i.MP4",(int)[[NSDate date] timeIntervalSince1970]]];
    NSURL *movieURL = [NSURL fileURLWithPath:pathToMovie];
    if([sender.title isEqualToString:@"录制"]) {
        sender.title = @"结束";
        NSLog(@"Start recording");
        
        [_datalist addObject:movieURL];
        
        unlink([pathToMovie UTF8String]); // 如果已经存在文件，AVAssetWriter会有异常，删除旧文件
        _movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:movieURL size:CGSizeMake(576, 1024)];
        _movieWriter.encodingLiveVideo = YES;
        [_videoCamera addTarget:_movieWriter];
        _videoCamera.audioEncodingTarget = _movieWriter;
        [_movieWriter startRecording];
        
    }else {
        sender.title = @"录制";
        NSLog(@"End recording");
        
        [_videoCamera removeTarget:_movieWriter];
        _videoCamera.audioEncodingTarget = nil;
        [_movieWriter finishRecording];
        
        if (_datalist.count==3) {
            NSURL *musicPath = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Skin" ofType:@"mp3"]];
            [self mergeVideo:[AVAsset assetWithURL:musicPath]];
        }
        
    }
}

-(void)mergeVideo:(AVAsset*)musciAsset {
    
    NSLog(@"正在合成到系统相册中");
    //    AVAsset *firstAsset = [AVAsset assetWithURL:firstVideoPath];
    //    AVAsset *secondAsset = [AVAsset assetWithURL:secondVideo];
    //    AVAsset *musciAsset = [AVAsset assetWithURL:musicPath];
    
    // 1 - Create AVMutableComposition object. This object will hold your AVMutableCompositionTrack instances.
    AVMutableComposition *mixComposition = [[AVMutableComposition alloc] init];
    // 2 - Video track
    AVMutableCompositionTrack *firstTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo
                                                                        preferredTrackID:kCMPersistentTrackID_Invalid];
    CMTime length = kCMTimeZero;
    AVAsset*tempAsset;
    for (NSURL*str in _datalist) {
        AVAsset*asset = [AVAsset assetWithURL:str];
        
        [firstTrack insertTimeRange:CMTimeRangeFromTimeToTime(kCMTimeZero, asset.duration)
                            ofTrack:[[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] atTime:length  error:nil];
        tempAsset = asset;
        length = CMTimeAdd(length, tempAsset.duration);
    }
    
    if (musciAsset!=nil){
        AudioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio
                                                 preferredTrackID:kCMPersistentTrackID_Invalid];
        [AudioTrack insertTimeRange:CMTimeRangeFromTimeToTime(kCMTimeZero, musciAsset.duration)
                            ofTrack:[[musciAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:kCMTimeZero error:nil];
    }else{
        NSDictionary *opts = [NSDictionary dictionaryWithObject:@(YES) forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
        NSURL *videoUrl = [[NSBundle mainBundle] URLForResource:@"abc" withExtension:@"mp4"];
        AVURLAsset * audioAsset = [[AVURLAsset alloc] initWithURL:videoUrl options:opts];
        AVMutableCompositionTrack * audioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
        AVAssetTrack * audioAssetTrack = [[audioAsset tracksWithMediaType:AVMediaTypeAudio] lastObject];
        
        [audioTrack insertTimeRange:CMTimeRangeFromTimeToTime(kCMTimeZero, length) ofTrack:audioAssetTrack atTime:kCMTimeZero error:nil];
    }
    
    
    // 4 - Get path
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *myPathDocs =  [documentsDirectory stringByAppendingPathComponent:
                             [NSString stringWithFormat:@"mergeVideo-%d.mov",arc4random() % 1000]];
    NSURL *url = [NSURL fileURLWithPath:myPathDocs];
    // 5 - Create exporter
    exporter = [[AVAssetExportSession alloc] initWithAsset:mixComposition
                                                presetName:AVAssetExportPresetHighestQuality];
    
    //修改背景音乐的音量start
    AVMutableAudioMix *videoAudioMixTools = [AVMutableAudioMix audioMix];
    if (musciAsset) {
        //调节音量
        //获取音频轨道
        AVMutableAudioMixInputParameters *firstAudioParam = [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:AudioTrack];
        //设置音轨音量,可以设置渐变,设置为1.0就是全音量
        [firstAudioParam setVolumeRampFromStartVolume:1.0 toEndVolume:1.0 timeRange:CMTimeRangeMake(kCMTimeZero, length)];
        [firstAudioParam setTrackID:AudioTrack.trackID];
        videoAudioMixTools.inputParameters = [NSArray arrayWithObject:firstAudioParam];
    }
    //end
    
    exporter.outputURL=url;
    exporter.outputFileType = AVFileTypeQuickTimeMovie;
    exporter.audioMix = videoAudioMixTools;
    exporter.shouldOptimizeForNetworkUse = YES;
    
    for (NSURL*item in _datalist) {
        unlink([item.absoluteString UTF8String]);
    }
    [_datalist removeAllObjects];
    
    [exporter exportAsynchronouslyWithCompletionHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self exportDidFinish];
        });
    }];
}

- (void)exportDidFinish{
    if (exporter.status == AVAssetExportSessionStatusCompleted) {
        NSURL *outputURL = exporter.outputURL;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            __block PHObjectPlaceholder *placeholder;
            if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(outputURL.path)) {
                NSError *error;
                [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
                    PHAssetChangeRequest* createAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:outputURL];
                    placeholder = [createAssetRequest placeholderForCreatedAsset];
                } error:&error];
                if (error) {
                    NSLog(@"%@",[NSString stringWithFormat:@"%@",error]);
                }
                else{
                    NSLog(@"视频已经保存到相册");
                }
            }else {
                NSLog(@"视频保存相册失败，请设置软件读取相册权限");
            }
        });
    }
    else{
        NSLog(@"%@",exporter.error);
        NSLog(@"裁剪失败");
    }
}

@end
